package LeetCode._02_数组;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class _438_找到字符串中所有字母异位词 {


    private HashMap<Character,Integer> need = new HashMap<>();
    private HashMap<Character,Integer> window = new HashMap<>();
    private List<Integer> res = new ArrayList<>();
    public List<Integer> findAnagrams(String s, String p) {
        if(s == null || p == null || s.length() == 0 || p.length() == 0) return new ArrayList<>();
        for (char c : p.toCharArray()) {
            need.put(c,need.getOrDefault(c,0)+1);
        }
        int left = 0,right = 0;
        int count = 0;

        while(right<s.length()){
            char c = s.charAt(right);
            right++;
            if(need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if(window.get(c).equals(need.get(c))){
                    count++;
                }
            }
            while(right - left >= p.length()){
                if(count == need.size()){
                    res.add(left);
                }
                char d = s.charAt(left);
                left++;
                if(need.containsKey(d)){
                    if(window.get(d).equals(need.get(d))){
                        count--;
                    }
                    window.put(d,window.get(d)-1);
                }
            }
        }
        return res;
    }
}
